﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArkanoidX
{
    public class ConfigParser
    {
        public String _content;
        public int Position;

        public String _bufferedLine;
        public bool _parsable;
        public String _varName;
        public String _varValue;

        public ConfigParser(String content)
        {
            _content = content;
            Position = 0;
            _parsable = false;
        }

        public void Reset()
        {
            Position = 0;
        }

        public bool EndOfString
        {
            get
            {
                return Position >= _content.Length;
            }
        }

        public String ReadLine()
        {
            StringBuilder sb = new StringBuilder();
            bool toend = false;

            if (EndOfString)
            {
                return null;
            }

            for (; Position < _content.Length; Position++)
            {
                if (toend)
                {
                    break;
                }
                char c = _content[Position];
                if (c == '\n')
                {
                    toend = true;
                }
                else if (c == '\r')
                {
                    toend = true;
                }
                else
                {
                    sb.Append(c);
                }
            }

            _bufferedLine = sb.ToString();
            TryProcessLine();

            return _bufferedLine;
        }

        void TryProcessLine()
        {
            int ip = Utility.GetAlphanumericWord(_bufferedLine, out _varName);

            if (ip < 0)
            {
                _parsable = false;
                return;
            }

            String tempLine = _bufferedLine.Substring(ip);

            ip = Utility.CompareString(tempLine, "=");

            if (ip < 0)
            {
                _parsable = false;
                return;
            }

            /**
             * be aware that the value must not include spaces at the beginning or at the end
             */
            _varValue = tempLine.Substring(ip).Trim();

            _parsable = true;
            return;
        }

        public bool IsCurrentLineParsable
        {
            get
            {
                return _parsable;
            }
        }

        public String VarName
        {
            get { return _varName; }
        }

        public String VarValue
        {
            get { return _varValue; }
        }
    }
}
